<template>
  <div class="login-page">
    <div class="action-box">
      <!-- 主题切换按钮 -->
      <global-theme style="margin-right: 20px"></global-theme>
    </div>
    <!-- 登录表单 -->
    <div class="mian-view-vessel">
      <div class="mian-view">
        <div class="left-view">
          <div class="top-box">
            <img class="logo-img" src="@/assets/images/logo/logo.svg" draggable="false" />
            <span class="text">袋鼠短剧后台{{ systemNameCpt }}系统</span>
          </div>
          <img class="inbetweening-img" src="@/assets/images/login/bg-login.svg" :draggable="false" />
        </div>
        <el-form ref="loginFormRef" class="right-view" labelPosition="left" statusIcon :model="loginForm" :rules="rules">
          <el-form-item class="global-slide-up-animation logo-box" style="animation-delay: 0.05s">
            <div class="title-box">
              <h1 class="title">登录</h1>
              <div class="subtitle">欢迎使用袋鼠短剧后台{{ systemNameCpt }}系统!</div>
            </div>
          </el-form-item>
          <el-form-item prop="username" class="global-slide-up-animation" style="animation-delay: 0.15s">
            <el-input
              v-model.trim="loginForm.username"
              :prefixIcon="IconUser"
              placeholder="请输入用户名"
              tabindex="1"
              :maxlength="usernameMax"
              type="url"
              clearable
              :inputStyle="{ height: '50px' }"
              @keydown.enter.stop.prevent="$throttle(handleLogin, $event)"
            ></el-input>
          </el-form-item>
          <el-form-item prop="password" class="global-slide-up-animation" style="animation-delay: 0.2s">
            <el-input
              v-model="loginForm.password"
              :prefixIcon="IconLock"
              placeholder="请输入密码"
              tabindex="2"
              showPassword
              :maxlength="passwordMax"
              type="password"
              :inputStyle="{ height: '50px' }"
              clearable
              @keydown.enter.stop.prevent="$throttle(handleLogin, $event)"
            ></el-input>
          </el-form-item>
          <el-form-item class="global-slide-up-animation" style="animation-delay: 0.25s">
            <el-button class="login-btn" :loading="loading" :disabled="loading" type="primary" @click="$throttle(handleLogin, $event)">登录</el-button>
          </el-form-item>
          <el-form-item class="global-slide-up-animation" style="animation-delay: 0.3s">
            <div style="display: flex; justify-content: flex-end; width: 100%">
              <el-button text type="primary" @click="$throttle(onpenfindPassword)">忘记密码</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
  <div class="fixed-bg-box">
    <div class="stars">
      <div class="star"></div>
      <div class="star" style="top: 80px; left: 800px; animation-delay: 3s"></div>
      <div class="star" style="top: 40px; left: 646px; animation-delay: 2s"></div>
      <div class="star" style="top: 120px; left: 395px; animation-delay: 4s"></div>
      <div class="star" style="top: 160px; left: 765px; animation-delay: 1s"></div>
      <div class="star" style="top: 170px; left: 1200px; animation-delay: 2s"></div>
      <div class="star" style="top: 200px; left: 1000px; animation-delay: 1s"></div>
    </div>
  </div>
  <div class="copyright-box">
    <rest-copyright></rest-copyright>
  </div>
  <find-password ref="findPasswordRef"></find-password>
</template>

<script setup lang="ts">
  import globalTheme from '@/layout/components/header/navbar/components/global-theme/global-theme.vue';
  import IconLock from '~icons/ep/lock';
  import IconUser from '~icons/ep/user';
  import { getUserInfoAxios, passdLoginAxios } from '@/api/login';
  import FindPassword from './components/find-password.vue';
  import { getPasswordRules, getUsernameRules } from '@/utils/page/rules';
  import type { FormRules } from 'element-plus';
  const findPasswordRef: $RefComp<typeof FindPassword> = ref(null);
  const router = useRouter();
  const route = useRoute();
  const userStore = useUserStore();
  const appStore = useAppStore();
  const loginFormRef: $RefComp<'ElForm'> = ref(null);
  const loginForm = shallowReactive({
    username: '',
    password: '',
  });
  const { usernameRules, usernameMax } = getUsernameRules();
  const { passwordMax, passwordRules } = getPasswordRules();

  const loading = shallowRef(false);
  const rules: FormRules = {
    username: usernameRules,
    password: passwordRules('密码'),
  };
  /**
   * 登录
   */
  async function handleLogin(event: Event) {
    if ('isComposing' in event && event.isComposing) {
      // 解决监听回车键中文状态下回车选择中文时也触发提交
      return;
    }
    try {
      await loginFormRef.value?.validate();
      loading.value = true;
      const res = await passdLoginAxios(JSON.parse(JSON.stringify(loginForm)));
      userStore.setAccessToken(res.data.accessToken);
      userStore.setRefreshToken(res.data.refreshToken);
      userStore.setRoleMenu(res.data.permissions);
      console.log('aaa====', res.data.roleId);
      if (res.data.roleId === 117) {
        appStore.setHomeRoute('/ledger-management/drama-data-statistics');
      } else {
        //查看有没有首页的权限
        const permissions = res.data.permissions || [];
        if (permissions[0] === '*') {
          appStore.setHomeRoute('/home');
        } else {
          if (permissions.indexOf('/home') !== -1) {
            appStore.setHomeRoute('/home');
          } else {
            let routeStr = '';
            for (const i of permissions) {
              const permissionArr = i.split('/');
              if (permissionArr && permissionArr.length > 1) {
                routeStr = permissions[0] || '';
                break;
              }
            }
            appStore.setHomeRoute(routeStr);
          }
        }
      }

      const res2 = await getUserInfoAxios();
      userStore.setUserInfo(res2.data);
      await router.push((route.query.redirect as string) || appStore.homeRoute);
      loading.value = false;
    } catch (err) {
      loading.value = false;
      console.log('错误====', err);
      ElToast.error(err.msg || '登录失败,BD002');
    }
  }

  onMounted(() => {
    if (import.meta.env.DEV) {
      loginForm.username = 'dsbbadmin';
      loginForm.password = 'dsbbadmin@123123';
    }
  });

  /**
   * 打开找回密码弹出框
   */
  function onpenfindPassword() {
    findPasswordRef.value?.show({ username: loginForm.username });
  }

  const systemNameCpt = computed(() => {
    return process.env.NODE_ENV === 'toufangxitong' ? '投放' : '管理';
  });
</script>

<style lang="scss" scoped>
  $item-height: 40px;

  @keyframes star-opacity {
    0% {
      opacity: 0;
    }

    40% {
      opacity: 1;
    }

    60% {
      opacity: 1;
    }

    100% {
      opacity: 0;
    }
  }
  @keyframes star-opacity {
    0% {
      opacity: 0;
    }

    40% {
      opacity: 1;
    }

    60% {
      opacity: 1;
    }

    100% {
      opacity: 0;
    }
  }
  @keyframes star-pos {
    0% {
      transform: scale(0) rotate(0) translate3d(0, 0, 0);
    }

    100% {
      transform: scale(1) rotate(0) translate3d(-450px, 450px, 0);
    }
  }

  @media screen and (max-width: 800px) {
    .left-view {
      display: none !important;
    }
  }

  .login-page {
    width: 100vw;
    height: 100vh;
    background: url('@/assets/images/login/page-bg-light.svg');
    background-attachment: fixed;
    background-size: cover;
    transition: background 0.2s;

    .action-box {
      @include flex(row, nowrap, center, center, center);
      position: absolute;
      top: 20px;
      right: 20px;
    }

    .mian-view-vessel {
      @include flex(row, nowrap, center, center, center);
      height: 100%;

      .mian-view {
        @include flex(row, nowrap, flex-start, stretch, stretch);
        height: min(70%, 460px);
        overflow: hidden;
        background: $c-bg-block;
        border-radius: 8px;
        box-shadow:
          0 12px 32px 4px rgba(0, 0, 0, 0.15),
          0 8px 20px rgba(0, 0, 0, 0.3);
        transition: background 0.2s;

        .left-view {
          @include flex(column, nowrap, space-between, center, stretch);
          width: 360px;
          padding: 30px 20px;
          background: $c-zs;

          .top-box {
            @include flex(column, nowrap, space-between, center, stretch);

            .logo-img {
              width: 120px;
            }

            .text {
              margin-top: 20px;
              font-size: 24px;
              font-weight: bold;
              color: #ffffff;
            }
          }

          .inbetweening-img {
            width: 240px;
          }
        }

        .right-view {
          @include flex(column, nowrap, space-between, center, center);
          width: min(80vw, 360px);
          padding: 30px 20px;

          .el-form-item {
            width: 100%;

            .title-box {
              .title {
                color: $c-text;
              }

              .subtitle {
                margin-top: 6px;
                color: $c-text-1;
              }
            }

            .login-btn {
              display: inherit;
              width: 100%;
              height: $item-height;
              margin-top: 5px;
              margin-bottom: -10px;
              font-size: 20px;
              font-weight: bold;
              box-shadow: 0 2px 12px 0 $c-box-shadow;
            }
          }
        }
      }
    }
  }
  // 流星动画
  .fixed-bg-box {
    position: fixed;
    top: 0;
    right: 0;
    z-index: 1;
    width: 100vh;
    height: 100vh;
    pointer-events: none;

    .stars {
      height: 0;

      .star {
        position: relative;
        top: 30px;
        right: 100px;
        z-index: 2;
        display: block;
        width: 5px;
        height: 5px;
        background: #0e17e9;
        border-radius: 50%;
        box-shadow: 0 0 5px 5px rgba(14, 23, 233, 0.3);
        opacity: 0;
        transform-origin: 100% 0;
        animation:
          star-opacity 5s infinite ease-in,
          star-pos 5s infinite ease-in;

        &:after {
          top: 0;
          left: 4px;
          display: block;
          content: '';
          border: 0 solid #0e17e9;
          border-color: transparent transparent transparent rgba(14, 23, 233, 0.3);
          border-width: 0 90px 2px;
          box-shadow: 0 0 1px 0 rgba(14, 23, 233, 0.1);
          transform: rotate(-45deg) translate3d(1px, 3px, 0);
          transform-origin: 0% 100%;
        }
      }
    }
  }

  html.dark .login-page {
    background: url('@/assets/images/login/page-bg-dark.svg');
    background-attachment: fixed;
    background-size: cover;

    .mian-view-vessel .mian-view {
      box-shadow: var(--el-box-shadow);
    }
  }

  .copyright-box {
    position: absolute;
    bottom: 0;
    z-index: 2;
    width: 100%;
    padding: 10px;
  }
</style>
